'use strict';
const { verifyJwt, loginResponse } = require('auth-token')
exports.main = async (event, context) => {
  // 需登录才能访问
  const payload = verifyJwt(event.token)
  if (!payload) {
    return loginResponse()
  }
  const currentUid = payload._id
  
  // 数据库连接
  const dbJQL = uniCloud.databaseForJQL({event, context})
  dbJQL.setUser({ // 指定后续执行操作的用户信息，此虚拟用户将同时拥有传入的uid、role、permission
    uid: 'currentUid', // 用户id
    role: [], // 指定当前执行用户的角色为admin。如果只希望指定为admin身份，可以删除uid和permission字段
    permission: ["auth.uid == doc.user_id"] // 用户权限
  })
  const affairCollection = dbJQL.collection('ume-affair')
  
	//event为客户端上传的参数
	console.log('event : ', event)
	switch (event.action) {
    case 'create':
      const affaireData = event.affair_data
      affaireData.user_id = currentUid
      const createRes = await affairCollection.add(affaireData)
      console.log('createRes:', createRes)
      if (createRes.id) {
        return {
          _id: createRes.id,
          message: '创建事务成功!'
        }
      } else {
        return {
          _id: undefined,
          message: createRes.errMsg
        }
      }
      break;
    case 'read':
      const params = event.params || {}
      const page = params.page || 1
      const pageSize = params.page_size || 50
      if (pageSize > 50) pageSize = 50
      // 已归档
      const isStore = params.is_store || false
      // 只看我的
      const isMe = params.is_me || false
      const startNum = (page - 1) * pageSize
      
      let conditions = `user_id=='${currentUid}'&& is_store==${isStore}`
      if (isMe) {
        conditions += '&& is_me==true'
      }
      console.log('conditions', conditions)
      const readRes = await affairCollection.where(conditions).orderBy('affair_date desc').skip(startNum).limit(pageSize).get()
      console.log('readRes : ', readRes)
      return {
        message: '查询成功!',
        data: readRes.data
      }
      break;
    case 'update':
      const updateRec = event.affair_data
      const upRes = await affairCollection.doc(updateRec._id).update(updateRec)
      return {
        message: '修改成功!',
        _id: updateRec._id
      }
      break;
    case 'delete':
      const deleteId = event._id
      // 查询是否子数据，有的话阻止删除
      const hasChildRes = await dbJQL.collection('affaire_portion').where(`affair_id=='${deleteId}'`).get({getOne: true})
      if (hasChildRes.data) {
        return {
          message: '请先删除相应详情记录再操作!',
          error: true,
        }
      }
      await affairCollection.where(`_id=='${deleteId}' && user_id=='${currentUid}'`).remove()
      return {
        error: false,
        message: '删除成功!'
      }
      break;
    case 'readOne':
      // 获取一条
      const readOneId = event._id
      const readOneRes = await affairCollection.doc(readOneId).get({getOne:true})
      return {
        message: '查询成功!',
        data: readOneRes.data
      }
      break;
    default:
      break;
  }
	//返回数据给客户端
	return event
};
